package com.leetcode;

public class No8 {
    public int myAtoi(String s) {
        if (s == null || s.isEmpty()) {
            return 0;
        }
        char[] charArray = s.toCharArray();
        boolean start = true;
        boolean negative = false;
        int res = 0;
        for (int i = 0; i < charArray.length; i++) {
            if (charArray[i] == ' ') {
                if (start) {
                    continue;
                }
                break;
            }
            if (charArray[i] == '-') {
                if (start) {
                    negative = true;
                    start = false;
                    continue;
                } else {
                    break;
                }
            }
            if (charArray[i] == '+') {
                if (start) {
                    start = false;
                    continue;
                } else {
                    break;
                }
            }
            if (charArray[i] >= '0' && charArray[i] <= '9') {
                int digit = charArray[i] - '0';
                if (negative) {
                    if (res > -(Integer.MIN_VALUE / 10) || (res == -(Integer.MIN_VALUE / 10) && digit >= -(Integer.MIN_VALUE % 10))) {
                        return Integer.MIN_VALUE;
                    }
                } else {
                    if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && digit >= Integer.MAX_VALUE % 10)) {
                        return Integer.MAX_VALUE;
                    }
                }
                res = res * 10 + digit;
                start = false;
            } else {
                break;
            }
        }
        return negative ? -res : res;
    }

    public static void main(String[] args) {
        No8 no8 = new No8();
        System.out.println(Integer.MIN_VALUE);
        System.out.println(Integer.MAX_VALUE);
        System.out.println(no8.myAtoi("-21474836482"));
    }
}
